package dao.impl;

import dao.BaseDao;
import dao.ComputerroomDao;
import entity.Computerroom;

import java.util.ArrayList;
import java.util.List;

public class ComputerroomDaoImpl extends BaseDao implements ComputerroomDao {
    @Override
    public int add(Computerroom computerroom) {
        int result=0;
        try{
            conn=getConnection();
            String sql="INSERT INTO `computerroom`(`roomName`, `computerNumber`, `manager`, `location`, `state`) VALUES (?, ?, ?,?, ?)";
            pstmt=conn.prepareStatement(sql);
            pstmt.setString(1,computerroom.getRoomName());
            pstmt.setInt(2,computerroom.getComputerNumber());
            pstmt.setString(3,computerroom.getManager());
            pstmt.setString(4,computerroom.getLocation());
            pstmt.setInt(5,computerroom.getState());
            result = pstmt.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            closeAll(conn,pstmt,rs);
        }
        return result;
    }

    @Override
    public int delete(int id) {
        int result=0;
        try{
            conn = getConnection();
            String sql="delete from computerroom where roomId=?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, id);
            result = pstmt.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            closeAll(conn,pstmt,rs);
        }
        return result;
    }

    @Override
    public List<Computerroom> list() {
        List<Computerroom> list=new ArrayList<>();
        try{
            conn = getConnection();
            String sql = "select * from computerroom order by computerNumber desc";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            while (rs.next()){
                Computerroom computerroom=new Computerroom();
                computerroom.setRoomId(rs.getInt("roomId"));
                computerroom.setRoomName(rs.getString("roomName"));
                computerroom.setComputerNumber(rs.getInt("computerNumber"));
                computerroom.setManager(rs.getString("manager"));
                computerroom.setLocation(rs.getString("location"));
                computerroom.setState(rs.getInt("state"));
                int i= rs.getInt("state");
                String stateNmae="";
                if (i==1){
                    stateNmae="使用中";
                }else if(i==2){
                    stateNmae="空闲中";
                }else{
                    stateNmae="维护中";
                }
                computerroom.setStateName(stateNmae);
                list.add(computerroom);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            closeAll(conn,pstmt,rs);
        }
        return list;
    }
}
